from git import Repo
from pathlib import Path
from datetime import datetime
import ast
import numpy as np

# 设置项目信息和链接
gitee_link = "https://gitee.com"
repo_name = "captcha"
repo_link = gitee_link + "/anji-plus/captcha"  # 新的仓库链接
commits_link = gitee_link + "/anji-plus/captcha/commits/master"
authors_link = gitee_link + "/anji-plus/captcha/contributors"
branches_link = gitee_link + "/anji-plus/captcha/branches"
branch_link = gitee_link + "/anji-plus/captcha/tree"

# 初始化报告
md = f"# {repo_name} Project Data Analysis\n\n "
md += "---\n\n"

try:
    # 克隆本地仓库
    if Path(repo_name).exists():
        repo = Repo(repo_name)
        print("已加载本地仓库")
    else:
        print("正在克隆远程仓库...")
        repo = Repo.clone_from(repo_link, repo_name)
        print("克隆完成!")

    # 获取提交历史
    repo_commits = list(repo.iter_commits())
    if not repo_commits:
        print("警告: 仓库中没有提交记录")
        exit(1)

    # 获取最早和最新提交
    first_commit = repo_commits[-1]
    latest_commit = repo_commits[0]

    # 转换时间戳为可读格式
    start_date = datetime.fromtimestamp(first_commit.authored_date).strftime("%Y-%m-%d %H:%M:%S")
    latest_date = datetime.fromtimestamp(latest_commit.authored_date).strftime("%Y-%m-%d %H:%M:%S")

    print(f"项目开始日期: {start_date}")
    print(f"最新更新日期: {latest_date}")

    # 添加基本信息到报告
    md += f"**Start Date**: {start_date}\n\n"
    md += f"**Latest Update**: {latest_date}\n\n"
    md += f"[**Commits**: {len(repo_commits)}]({commits_link})\n\n"

    # 分支分析 - 添加非法分支名称过滤
    gitee = repo.remotes[0]
    gitee_branches = [
        ref.name[7:] for ref in gitee.refs if ref.name != "origin/HEAD"
    ]

    gitee_branches.remove("master")
    repo_branches = ["master"] + gitee_branches
    md += f"[**Branches:** {len(repo_branches)}]({branches_link})\n\n"

    # 作者分析
    author_data = {}
    for commit in repo_commits:
        author = commit.author.name
        author_data[author] = author_data.get(author, 0) + 1

    author_data = sorted(author_data.items(), key=lambda x: x[1], reverse=True)
    md += f"[**Authors**: {len(author_data)}]({authors_link})\n\n"

    # 添加分支列表到报告
    md += "## Branches\n\n"
    for branch in repo_branches:
        md += f"- [{branch}]({branch_link + branch})\n\n"

    # 添加作者排行榜到报告
    md += "## Top 10 Authors\n\n"
    for i in range(min(10, len(author_data))):
        author = author_data[i]
        name = author[0].replace(" ", "")
        commits = author[1]
        md += f"{i + 1}. [{name}]({gitee_link}/{name}): {commits} commits\n\n"  # 修正URL格式


    # -------------------- 新增：提交统计分析 --------------------
    # 初始化数据存储列表
    lines_changed = []  # 每次提交修改的行数
    files_changed = []  # 每次提交修改的文件数
    commit_stats = []  # 提交统计原始数据

    # 解析统计数据
    for commit in repo_commits:
        stats = commit.stats.total  # 将字符串安全转换为字典
        total_lines = stats.get('insertions',0)+stats.get('deletions',0)
        lines_changed.append(total_lines)
        files_changed.append(stats.get('files',0))

    # 添加提交统计分析到报告
    md += "## Commit Stats\n\n"

    # 使用NumPy计算统计指标（转换为整数便于阅读）
    if lines_changed and files_changed:
        lines_changed = np.array(lines_changed)
        files_changed = np.array(files_changed)
        mean_lines_changed = int(np.mean(lines_changed))
        median_lines_changed = int(np.median(lines_changed))
        mean_files_changed = int(np.mean(files_changed))
        median_files_changed = int(np.median(files_changed))

        # 将统计结果添加到报告
        md += f"**Average Lines Changed / Commit**: {mean_lines_changed}\n\n"
        md += f"**Median Lines Changed / Commit**: {median_lines_changed}\n\n"
        md += f"**Average Files Changed / Commit**: {mean_files_changed}\n\n"
        md += f"**Median Files Changed / Commit**: {median_files_changed}\n\n"
    else:
        md += "无法计算提交统计数据: 没有可用的数据\n\n"

    # 写入Markdown文件
    Path("report-captcha.md").write_text(md, "UTF-8")
    print("报告生成完成!")

except Exception as e:
    print(f"执行过程中发生错误: {e}")
    # 打印详细的错误堆栈信息，帮助调试
    import traceback

    print(traceback.format_exc())